package com.eco.fishway.service;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: xulinyu
 * Created at: 2024/8/9 14:20
 */
@Slf4j
@Service
public class VideoFileService {

    @Value("${fishdata.video.path:}")
    private String videoPath;

    @Value("${fishdata.video.url-prefix}")
    private String videoUrlPrefix;

    @Value("${fishdata.video.max-count:}")
    private Integer maxVideoCount;

    @Value("${fishdata.video.normal_in_prefix:}")
    private String normalInPrefix;

    @Value("${fishdata.video.normal_out_prefix:}")
    private String normalOutPrefix;

    @Value("${fishdata.video.normal_path:}")
    private String normalPath;

    private static final String[] VIDEO_EXTENSIONS = {"mp4", "avi", "mkv", "mov", "flv", "wmv"};

    private final ThreadPoolExecutor executor;

    public VideoFileService(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public List<String> findAllVideos() {
        if (StringUtils.isEmpty(videoPath)) {
            return Lists.newArrayList();
        }
        File directory = new File(videoPath);
        List<String> videoFiles = Lists.newArrayList();
        findVideos(directory, videoFiles);
        return videoFiles;
    }

    private void findVideos(File directory, List<String> videoFiles) {
        if (videoFiles.size() >= maxVideoCount) {
            return; // 达到最大数量后停止递归
        }
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null || videoFiles.size() >= 2) {
                for (File file : files) {
                    if (videoFiles.size() >= maxVideoCount) {
                        return; // 再次检查以防多余的递归
                    }
                    if (file.isDirectory()) {
                        // 递归搜索子目录
                        findVideos(file, videoFiles);
                    } else {
                        for (String extension : VIDEO_EXTENSIONS) {
                            if (file.getName().toLowerCase().endsWith(extension)) {
                                String filename = videoUrlPrefix + file.getName();
                                videoFiles.add(filename);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 批量删除文件
     * @param filePaths
     */
    public void deleteBatchFiles(List<String> filePaths) {
        filePaths.forEach(x->{
            CompletableFuture.runAsync(() -> {
                //连文件夹一起递归删除
                deleteDirectory(new File(modifyUrl(x)));
            }, executor);
        });
    }

    /**
     * 修改文件地址为文件夹地址
     * 例如：http://192.168.1.31:8089/statici/npsin/20240627103659/v20240627103659.mp4
     * 修改后： http://192.168.1.31:8089/statici/npsin/20240627103659
     * @param url
     * @return
     */
    private String modifyUrl(String url) {
        // 根据操作系统选择正确的分隔符
        String separator = File.separator;
        // 找到最后一个斜杠的位置
        int lastSlashIndex = url.lastIndexOf(separator);

        // 截取到最后一个斜杠前的部分
        if (lastSlashIndex != -1) {
            return url.substring(0, lastSlashIndex+1);
        } else {
            // 如果没有找到斜杠，返回原始字符串
            return url;
        }
    }


    /**
     * 删除单个文件
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return false;
    }

    private static boolean deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file); // 递归删除子目录
                } else {
                    file.delete(); // 删除文件
                }
            }
        }
        return directory.delete(); // 最后删除空目录
    }

    /**
     * 替换文件地址
     * @param url
     * @return
     */
    public String convertUrlToFilePath(String url) {
        String filePath = url;
        // 根据操作系统选择正确的分隔符
        String separator = File.separator;

        if (url.contains(normalInPrefix)) {
            filePath = url.replace(normalInPrefix, normalPath);
        } else if (url.contains(normalOutPrefix)) {
            filePath = url.replace(normalOutPrefix, normalPath);
        }

        // 确保路径使用正确的分隔符
        filePath = filePath.replace("/", separator).replace("\\", separator);
        log.info("删除文件地址：{}",filePath);
        return filePath;
    }

}
